// stores/spaceStore.js
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import axios from 'axios'

export const useSpaceStore = defineStore('space', () => {
  // 状态定义
  const spaces = ref([])
  const currentFilter = ref({
    status: '',
    minRent: null,
    maxRent: null,
    sortBy: 'endDate'
  })

  // 计算属性
  const filteredSpaces = computed(() => {
    return spaces.value
      .filter((space) => {
        return (
          !currentFilter.value.status ||
          space.status === currentFilter.value.status
        )
      })
      .sort((a, b) => {
        if (currentFilter.value.sortBy === 'rent') {
          return a.rentAmount - b.rentAmount
        }
        return new Date(a.endDate) - new Date(b.endDate)
      })
  })

  // 异步方法
  const fetchSpaces = async () => {
    try {
      const { data } = await axios.get('/api/spaces')
      spaces.value = data
    } catch (error) {
      console.error('获取空间数据失败:', error)
    }
  }

  const updateSpaceStatus = async (id, newStatus) => {
    try {
      await axios.patch(`/api/spaces/${id}`, { status: newStatus })
      await fetchSpaces()
    } catch (error) {
      console.error('更新状态失败:', error)
      throw error
    }
  }

  return {
    spaces: filteredSpaces,
    currentFilter,
    fetchSpaces,
    updateSpaceStatus
  }
})
